package net.pimpas.web.jsf.renderers.select.ajax;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UISelectMany;
import javax.faces.component.UISelectOne;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import net.pimpas.util.reflection.ReflectionUtil;
import net.pimpas.web.jsf.renderers.AjaxRendererBase;
import net.pimpas.web.jsf.renderers.RendererBase;
import net.pimpas.web.jsf.util.ComponentUtils;

import org.apache.myfaces.shared_impl.renderkit.RendererUtils;
import org.apache.myfaces.shared_impl.renderkit.html.HtmlRendererUtils;

public class AjaxSelectRenderer extends RendererBase implements AjaxRendererBase {
	
	public static final String JAVASCRIPT_HANDLER	= "pimpas.AJAX.Populate.Select";
	
	public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
		if(!component.isRendered()) return;
		if(!ComponentUtils.isCorrectComponentType(component, UIInput.class)) return;
		
		/**
		 * myfaces 1.1.5-SNAPSHOT code
		 */
		// TODO its the only way?
		List selectItemList = null;;
		Converter converter;
		boolean selectMany = ReflectionUtil.isSubclass(component.getClass(), UISelectMany.class); 
		if (selectMany) {
            selectItemList = org.apache.myfaces.shared_impl.renderkit.RendererUtils
                    .getSelectItemList((UISelectMany) component);
            converter = HtmlRendererUtils.findUISelectManyConverterFailsafe(context, component);
        } else {
            selectItemList = RendererUtils
                    .getSelectItemList((UISelectOne) component);
            converter = HtmlRendererUtils.findUIOutputConverterFailSafe(context, component);
        }
		
        Set lookupSet = HtmlRendererUtils.getSubmittedOrSelectedValuesAsSet(selectMany, component, context, converter);
        HtmlRendererUtils.renderSelectOptions(context, component, converter, lookupSet, selectItemList);
		
		/**
		 * end myfaces 1.1.5-SNAPSHOT code
		 */
	}
	

	public String getJavascriptHandler() {
		return JAVASCRIPT_HANDLER;
	}


	public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
	}


	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
	}
}